//
//  FriendAddViewController.m
//  SportSocial
//
//  Created by yull on 15/3/12.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "FriendAddViewController.h"
#import "UserNet.h"
#import "NearUserCell.h"
#import "UIScrollView+PullToRefresh.h"
#import "NDRefreshControl.h"
#import "NDRefreshLoadMoreContainView.h"

#define Add_User_Page_Size    10

@interface FriendAddViewController () <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *userTableView;

@property (nonatomic, strong) NSMutableArray *userArray;

@property (nonatomic, assign) NSInteger currentPage;
@property (nonatomic, assign) NSInteger totalPage;

@property (nonatomic, strong) UISearchBar *userSearchBar;
@end

@implementation FriendAddViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"添加好友";
    
    [self addCommonBackButton];
    
    [self initSearchBar];
    
    self.userTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, self.view.width, self.view.height-40-Navibar_Height)];
    self.userTableView.dataSource = self;
    self.userTableView.delegate = self;
    self.userTableView.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:self.userTableView];
}

- (void)addRefreshAndLoadMore
{
    if (!self.userTableView.refreshControl && !self.userTableView.loadMoreControl) {
        @weakify(self);
        [self.userTableView nd_addPullToRefreshWithActionHandler:^(id sender) {
            @strongify(self);
            self.currentPage = 0;
            
            [self searchUserWithName:self.userSearchBar.text];
        } loadMoreWithActionHandler:^(id sender) {
            @strongify(self);
            [self searchUserWithName:self.userSearchBar.text];
        }];
    }
}

- (void)removeRefreshAndLoadMore
{
    [self.userTableView.refreshControl removeFromSuperview];
    [self.userTableView.loadMoreControl removeFromSuperview];
}

- (void)initSearchBar
{
    self.userSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    self.userSearchBar.delegate = self;
    self.userSearchBar.showsCancelButton = YES;
    self.userSearchBar.translucent = NO;
    self.userSearchBar.tintColor = [UIColor blackColor];
    [self.view addSubview:self.userSearchBar];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.userArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [NearUserCell nearCellDefaultHeight];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *nearUserIdentifier = @"SearchUser";
    NearUserCell *nearUserCell = [tableView dequeueReusableCellWithIdentifier:nearUserIdentifier];
    
    if (!nearUserCell) {
        nearUserCell = [[NearUserCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nearUserIdentifier];
        nearUserCell.distanceLabel.hidden = YES;
    }
    
    NearUser *nearUser = [self.userArray objectAtIndex:indexPath.row];
    
    [nearUserCell drawCellWithNearUser:nearUser];
    
    return nearUserCell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NearUser *nearUser = [self.userArray objectAtIndex:indexPath.row];
    
    UIViewController *infoViewController = [Interface createUserInfoViewControllerWithUserId:nearUser.userId userName:nearUser.name];
    [self.navigationController pushViewController:infoViewController animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Net
- (void)searchUserWithName:(NSString *)text
{
    [self showHUD];
    
    [UserNet searchUserWithName:text pageNumber:self.currentPage + 1 pageSize:Add_User_Page_Size successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [self hideHUD];
        [self endLoad];
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *datadic = [responseObject objectForKey:@"data"];
            NSArray *listArray = [datadic objectForKey:@"list"];
            
            if (self.currentPage == 0) {
                [self.userArray removeAllObjects];
            }
            
            self.currentPage = [[datadic objectForKey:@"pageNumber"] integerValue];
            self.totalPage = [[datadic objectForKey:@"totalPage"] integerValue];
            
            for (NSDictionary *dict in listArray) {
                [self.userArray addObject:[NearUser userWithDict:dict]];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                if (self.currentPage == self.totalPage) {
                    //((NDRefreshLoadMoreContentView *)(self.userTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNoMore;
                    [self removeRefreshAndLoadMore];
                } else {
                    ((NDRefreshLoadMoreContentView *)(self.userTableView.loadMoreControl.containView)).loadMoreFlag = NDRefreshLoadMoreNormal;
                    [self addRefreshAndLoadMore];
                }
                [self.userTableView reloadData];
                
                if (!self.userArray.count) {
                    [self showText:@"没有搜索到相关数据"];
                }
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self hideHUD];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self endLoad];
            [self showText:@"网络连接失败" time:2];
        });
    }];
}

- (void)endLoad
{
    [self.userTableView nd_endLoadMore];
    [self.userTableView nd_endRefreshing];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    NSString *text = searchBar.text;
    text = [text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (text.length > 0) {
        if (!self.userArray) {
            self.userArray = [NSMutableArray array];
        }
        
        self.currentPage = 0;
        self.totalPage = 0;
        
        [self searchUserWithName:text];
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    searchBar.text = @"";
    [searchBar resignFirstResponder];
}

@end
